import json
import traceback

import requests
from django.conf import settings
from django.contrib import auth
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render

# Create your views here.
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt

from oauth.common import gpub
from oauth.common.RsaCommon import RsaCommon
from user.models import Oauth2ProviderUser


def login(request):
    '''
    用户登录操作
    :param request:
    :return:
    '''
    if request.method == 'POST':
        # here you get the post request username and password
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')

        # 检测用户是否在 oauth2_provider_user表中存在
        _user_list = Oauth2ProviderUser.objects.filter(username = username)
        if not _user_list:
            return render(request, 'user/login.html', {'form': {'errors': True, 'message': u'用户权限不足!'}})
        # authentication of the user, to check if it's active or None
        # 此处需要检测 Oauth2ProviderUser 表，目前检测的是 auth_user 表，以后根据需要修改
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                # this is where the user login actually happens, before this the user
                # is not logged in.
                auth.login(request, user)
                return HttpResponseRedirect(reverse('user_profile'))
        else:
            return render(request, 'user/login.html', {'form':{'errors':True}})
    return render(request, 'user/login.html')

@csrf_exempt
def get_sms_code(request):
    '''
    得到短信验证码
    :param request:
    :return:
    '''
    host = settings.MAIN_SITE_HOST
    ret = {'retcode': 'FAIL', 'message': 'params error!'}
    try:
        dataParam = {}
        dataParam['phone'] = request.POST.get('phone')
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        url = host + "/baidu_dueros/send_sms"
        response = requests.post(url, data=json.dumps(dataParam), headers=headers)
        #ret = response._content.decode('utf-8')
        ret_byte = response._content
        return HttpResponse(ret_byte,
                            content_type="application/json;charset=utf-8")
    except Exception as e:
        gpub.log_error.error('get_sms_code error')
        #gpub.log_error.error(e)
        gpub.log_error.error(traceback.format_exc())
    return HttpResponse(json.dumps(ret),
                        content_type="application/json;charset=utf-8")


def _register_user(phone='', password=''):
    '''
    调用远程post，注册新用户
    :param phone:
    :param password:
    :return:
    '''
    ret = {'retcode': 'FAIL', 'message': 'params error!'}
    try:
        host = settings.MAIN_SITE_HOST
        dataParam = {'phone': phone, 'password': password}
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        url = host + "/baidu_dueros/baidu_login"
        response = requests.post(url, data=json.dumps(dataParam), headers=headers, verify=False)
        #print(response._content)
        ret = json.loads(response._content.decode('utf-8'))
    except Exception as e:
        #print(e)
        # 有异常不影响正常流程
        gpub.log_error.error('_register_user error')
        gpub.log_error.error(traceback.format_exc())
    return ret


def _check_sms_code(phone, sms_code):
    '''
    检测验证码(读取redis)
    :param request:
    :return:
    '''
    ret = False
    try:
        _sms_code = gpub.redis3.get("captcha_%s" % phone)
        if _sms_code and _sms_code.decode('utf-8') == sms_code:
            pipe = gpub.redis3.pipeline()
            # 删除手机验证码
            pipe.delete("captcha_%s" % phone)
            pipe.execute()
            ret = True
    except:
        gpub.log_error.error('_check_sms_code error')
        gpub.log_error.error(traceback.format_exc())
    return ret


@csrf_exempt
def login_sms(request):
    '''
    短信验证码登录
    :param request:
    :return:
    '''
    try:
        phone = request.POST.get('phone', '')
        sms_code = request.POST.get('sms_code', '')
        # 检测验证码
        if not _check_sms_code(phone, sms_code):
            return HttpResponse(json.dumps({'retcode': 'FAIL', 'message': '验证码错误!'}, ensure_ascii=False),
                                content_type="application/json;charset=utf-8")

        # 检测用户是否存在，不存在，创建新用户
        _user_list = User.objects.filter(username=phone)
        if not _user_list:  # not exists then register
            _reg_ret = _register_user(phone=phone)
            if _reg_ret['retcode'] == 'FAIL':
                return HttpResponse(json.dumps({'retcode': 'FAIL', 'message': '网络异常，请稍后再试。'}, ensure_ascii=False),
                                    content_type="application/json;charset=utf-8")

        _user = User.objects.get(username=phone)
        auth.login(request, _user)

        return HttpResponse(json.dumps({'retcode': 'SUCC', 'message': '登录成功'}, ensure_ascii=False),
                            content_type="application/json;charset=utf-8")
    except Exception as e:
        print(e)
        gpub.log_error.error('login_sms error')
        gpub.log_error.error(traceback.format_exc())
        return HttpResponse(json.dumps({'retcode': 'FAIL', 'message': '服务器开小差，请重新打开。'}, ensure_ascii=False),
                            content_type="application/json;charset=utf-8")


def profile(request):
    if request.user.is_anonymous:
        return HttpResponseRedirect(reverse('user_login'))

    data_params = {'username': request.user.username, 'user_reg_type': 0,
                   'company': {'name': '', 'website': '', 'desc': '', 'addr': '', 'contact_username': '', 'phone': '',
                               'email': ''}}
    try:
        oauth_user = Oauth2ProviderUser.objects.get(user_id=request.user.id)
        data_params['user_reg_type'] = oauth_user.type
    except:
        pass
    return render(request, 'user/profile.html', data_params)

